package impl.service;

import impl.MySQL;
import model.ResponseBodyMessage;
import model.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserSql {
    private final static String USER_MESSAGE = "select * from user where username = ?";//查询账户信息
    private final static String USER_SIGN = "insert into user (username,password) value (?,?)";//注册用户账号密码
    private final static MySQL mySQL;

    static {
        try {
            mySQL = new MySQL();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    ;
    public User userToPassword(String username) throws SQLException {
        List<User> users = selectUser(username);
        if (users.size() == 0){
            System.out.println("账户不存在");
            return null;
        }else if (users.size() == 1){
            return users.get(0);
        }else {
            System.out.println("数据库错误");
            return null;
        }
    }
    public ResponseBodyMessage<Integer> sign(String username, String password) throws SQLException {
        List<User> users = selectUser(username);
        if (!users.isEmpty()){
            System.out.println("账户已存在");
            return new ResponseBodyMessage<>(false,"账户已存在",-1);
        }
        PreparedStatement statement = mySQL.getStatement(USER_SIGN);
        statement.setString(1,username);
        statement.setString(2,password);
        int n = statement.executeUpdate();
        if (n == 1){
            users = selectUser(username);
            User user = users.get(0);
            System.out.println(user);
            return new ResponseBodyMessage<>(true,"注册成功",user.getId());
        }else {
            return new ResponseBodyMessage<>(false,"注册失败",-1);
        }
    }

    private List<User> selectUser(String username) throws SQLException {
        PreparedStatement statement = mySQL.getStatement(USER_MESSAGE);
        statement.setString(1,username);
        ResultSet resultSet = statement.executeQuery();
        List<User> users = new ArrayList<>();
        while (resultSet.next()) {
            User user = new User();
            user.setPassword(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            user.setId(resultSet.getInt("id"));
            users.add(user);
        }
        resultSet.close();
        statement.close();
        return users;
    }
}
